var express = require('express');
var router = express.Router();
var fs = require('fs');
var multer = require('multer');
var path = require('path');
var path1 = path.resolve("public/uploads/images/" + db.yymmdd() + "/");
var BaseData = require('.././config/db');
db = new BaseData();

var upload = multer({
		dest: 'public/uploads/upload_tmp/'
	}),
	uploads = "public/uploads/images/" + db.yymmdd() + "/",
	uploadfile = "/uploads/images/" + db.yymmdd() + "/";

//提交内容
router.post('/publish_post', function(req, res, next) {
	if(req.session.SubStop) {
		res.json({
			"code": "3001",
			"msg": "您违反了投稿规定,已被被禁止投稿！"
		})
		return false;
	}
	if(req.session.token) {
		var Content = db.DefenseXSS(req.body.Content),
			ContentType = db.DefenseXSS(req.body.ContentType),
			ContentAnnex = db.DefenseXSS(req.body.ContentAnnex),
			msg = "";
		if(!Content) {
			msg = "内容不能少于10个字";
		} else if(ContentType != 3 && ContentType != 2 && ContentType != 1) {
			msg = "内容类型错误";
		} else if(ContentType == 2 && ContentAnnex.length <= 0 || ContentType == 3 && ContentAnnex.length <= 0) {
			msg = "附件错误";
		} else if(Content.length > 300) {
			msg = "内容长度不能超过300个字！";
		} else if(ContentAnnex.length > 61) {
			msg = "上传的文件路径过长!";
		}
		if(msg) {
			res.json({
				"code": "3001",
				"msg": msg
			})
		} else {
			//解密用户id
			var Str = req.session.token;
			var User_id = db.Toolaes(Str.toString().split("_")[0], "Decrypt");
			db.connection.query('SELECT count(*) FROM `subinfo` WHERE ?', ['1'], function(err, rows) {
				if(err) {
					res.json({
						"code": "3002",
						"msg": "系统出现错误,请联系管理员"
					})
				} else {
					//生成内容id
					var time = String((new Date()).valueOf());
					var Sub_id = "s" + time.substring(3, time.length) + (parseInt(rows[0]['count(*)']) + 1)
					if(Sub_id) {
						if(ContentType == 1) {
							ContentAnnex = null;
						}
						console.log(Sub_id, User_id, Content, ContentType, ContentAnnex, new Date().toLocaleString())
						db.connection.query('INSERT INTO subinfo(Sub_id,User_id,Content,ContentType,ContentAnnex,SubTime) value(?,?,?,?,?,?)', [Sub_id, User_id, Content, ContentType, ContentAnnex, new Date().toLocaleString()], function(err, rows) {
							if(err) {
								res.json({
									"code": "3003",
									"msg": "请稍后重新提交"
								})
							} else {
								if(rows) {
									res.json({
										"code": "3000",
										"msg": "success"
									})
								}
							}
						});
					}
				}
			});
		}
	} else {
		res.json({
			"code": "3004",
			"msg": "请登录后再操作"
		})
	}

})

//上传图片
router.post('/upload', upload.any(), function(req, res, next) {
	if(req.session.token || req.session.admintoken) {
		//解密用户id
		var ImgType = "";
		// 获得文件的临时路径
		//	var tmp_path = req.files.thumbnail.path;
		//加密:encryption  解密:Decrypt
		fs.exists(path1, function(exists) {
			if(!exists) {
				fs.mkdir(uploads, function(err) {
					if(err)
						console.error(err);
					console.log('创建目录成功');
				});
			}
		});
		if(!db.checkImgType(req.files[0].originalname.toLowerCase())) {
			res.json({
				code: '3001',
				msg: '图片格式有误'
			})
			return false;
		}
		if(!db.ImageSize(req.files[0].size, 2)) {
			res.json({
				code: '3002',
				msg: '图片过大，请不要超过' + 2 + 'mb'
			})
			return false
		}
		ImgType = db.upfilename(req.files[0].originalname);
		var filename = db.filename() + ImgType.toLowerCase();
		var des_file = uploads + filename,
			fileurl = uploadfile + filename;
		fs.readFile(req.files[0].path, function(err, data) {
			fs.writeFile(des_file, data, function(err) {
				if(err) {
					console.log(err);
				} else {
					response = {
						code: '0',
						msg: "success",
						file: fileurl
					};
					res.json(response);
				}
			});
		});
	} else {
		res.json({
			"code": "3004",
			"msg": "请登录后再操作"
		})
	}
})

//上传图片
router.post('/uploads', upload.any(), function(req, res, next) {
	var ImgType = "";
	// 获得文件的临时路径
	//	var tmp_path = req.files.thumbnail.path;
	//加密:encryption  解密:Decrypt
	fs.exists(path1, function(exists) {
		if(!exists) {
			fs.mkdir(uploads, function(err) {
				if(err)
					console.error(err);
				console.log('创建目录成功');
			});
		}
	});
	if(db.checkImgType(req.files[0].originalname)) {
		res.json({
			code: '3001',
			msg: '图片格式有误'
		})
		return false;
	}
	if(!db.ImageSize(req.files[0].size, 5)) {
		res.json({
			code: '3002',
			msg: '图片过大，请不要超过' + 5 + 'mb'
		})
		return false
	}
	ImgType = db.upfilename(req.files[0].originalname);
	var filename = db.filename() + ImgType;
	var des_file = uploads + filename,
		fileurl = uploadfile + filename;
	fs.readFile(req.files[0].path, function(err, data) {
		fs.writeFile(des_file, data, function(err) {
			if(err) {
				console.log(err);
			} else {
				response = {
					code: '0',
					msg: "success",
					file: fileurl
				};
				res.json(response);
			}
		});
	});
})

module.exports = router;